﻿namespace YidanSoft.Library.EditorUtility.WinControls
{
    using System;
    using System.Drawing;
    using System.Windows.Forms;

    public class NumericTextBox : TextBox
    {
        private string lastChar;
        private int maximum = -1;
        private int minimum = -1;
        private bool useRange = false;

        public NumericTextBox()
        {
            this.InitializeComponent();
        }

        private void InitializeComponent()
        {
            base.TextChanged += new EventHandler(this.NumericTextBox_TextChanged);
        }

        private void NumericTextBox_TextChanged(object sender, EventArgs e)
        {
            if (this.useRange && (this.Text != ""))
            {
                int num = Convert.ToInt32(this.Text);
                if (num > this.maximum)
                {
                    this.Text = this.maximum.ToString();
                }
                else if (num < this.minimum)
                {
                    this.Text = this.minimum.ToString();
                }
                if (this.Text.Length == 1)
                {
                    this.lastChar = this.Text;
                }
            }
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            base.OnKeyPress(e);
            if ((char.IsLetter(e.KeyChar) || char.IsPunctuation(e.KeyChar)) || char.IsSeparator(e.KeyChar))
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }

        protected override void OnLostFocus(EventArgs e)
        {
            base.OnLostFocus(e);
            if ((this.Text.Length == 0) && this.useRange)
            {
                this.Text = this.lastChar;
            }
        }

        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);
        }

        public Size SetRange
        {
            get
            {
                if (this.useRange)
                {
                    return new Size(this.minimum, this.maximum);
                }
                return new Size(-1, -1);
            }
            set
            {
                this.minimum = value.Width;
                this.maximum = value.Height;
                this.useRange = true;
            }
        }
    }
}

